<?php
// +---------------------------------------------------------------------------+
// | This file is part of the KnowledgebasePublisher package                   |
// | KnowledgebasePublisher - web based knowledgebase publisher tool           |
// |                                                                           |
// | Author:  Evgeny Leontev <eleontev@gmail.com>                              |
// | Copyright (c) 2005 Evgeny Leontev                                         |
// |                                                                           |
// | For the full copyright and license information, please view the LICENSE   |
// | file that was distributed with this source code.                          |
// +---------------------------------------------------------------------------+

require_once APP_ROOT_DIR . 'tools/FCKeditor/fckeditor.php';
require_once 'core/app/AppAjax.php';
require_once 'core/common/CommonEntryView.php';


class KBEntryView_form extends AppView
{
	
	//var $template = 'form_tab.html';
	var $template = 'form.html';
	
	
	function execute(&$obj, &$manager) {
		
		$this->addMsg('user_msg.ini');
	
		$tpl = &new tplTemplatez($this->template_dir . $this->template);
		$tpl->tplAssign('error_msg', AppMsg::errorBox($obj->errors));
		
		
		$oFCKeditor = new FCKeditor('body');
		
		if(!$oFCKeditor->IsCompatible()) {
			$this->controller->go('editor_incompatible', true);
		}
		
		$oFCKeditor->BasePath = APP_HOME_PATH . 'tools/FCKeditor/';
		$oFCKeditor->ToolbarSet = 'Knowledgebase';		
		$oFCKeditor->Width  = '100%' ;
		$oFCKeditor->Height = '300' ;
		$oFCKeditor->Value	= &$obj->get('body');	
		
		$tpl->tplAssign('vck_editor', $oFCKeditor->CreateHtml());		
		
		
		// categories
		$categories = &$this->stripVars($manager->getCategoryRecords());
		$range = &$manager->getCategorySelectRange($categories);
		$category_id = ($obj->getCategory()) ? current($obj->getCategory()) 
		                                     : array(current(array_keys($range)));
		
		$select = new FormSelect();
		$select->select_tag = false;
		$select->setRange($range);
		
		foreach($categories as $k => $v) {
			if($v['private']) {
				$select->setOptionParam($k, 'style="color: #cc0033;"');
			}
		}
		
		$tpl->tplAssign('category_select', $select->select($category_id));
		
		$select->setRange($range);		
		$tpl->tplAssign('category_mirror_select', $select->select($obj->getCategoryMirror()));
		
		
		
		//related
		foreach($obj->getRelated() as $id => $title) {
			$data = array('article_id'=>$id, 'title'=>$title);
			$data['delete_msg'] = $this->msg['delete_msg'];
			$data['sure_common_msg'] = $this->msg['sure_common_msg'];
			$data['insert_as_link_msg'] = $this->msg['insert_as_link_msg'];
			$tpl->tplParse($data, 'related_row');
		}
		
		
		//attachment		
		foreach($obj->getAttachment() as $id => $filename) {
			$data = array('attachment_id'=>$id, 'filename'=>$filename);
			$data['delete_msg'] = $this->msg['delete_msg'];
			$data['sure_common_msg'] = $this->msg['sure_common_msg'];
			$data['insert_as_link_msg'] = $this->msg['insert_as_link_msg'];
			$tpl->tplParse($data, 'attachment_row');
		}
		
		
		// member roles
		if($manager->isExtra('private')) {
			require_once APP_EXTRA_MODULE_DIR . 'private/PrivateEntry.php';
			PrivateEntry::getFormStaff($tpl, $manager);
		}
		
		
		// sort order
		ini_set('arg_separator.output', '&amp;'); // required for IIS

		$this->manager = &$manager;
		$this->obj = &$obj;
		$xajax = &new AppAjax();
		//$xajax->debugOn();
		$xajax->setRequestURI($this->controller->getLink('all'));
		$xajax->setCharEncoding($this->encoding);
		$xajax->decodeUTF8InputOn();
		$xajax->registerFunction(array('populateSelect', $this, 'ajaxPopulateSortSelect'));
		$xajax_js = $xajax->getJavascript();
		$xajax->processRequests();
		$tpl->tplAssign('xajax_js', $xajax_js);
		
		
		$entries = $manager->getSortRecords($category_id);
		$select->resetOptionParam();
		$select->setRange($this->stripVars($this->getSortSelectRange($entries)));
		$tpl->tplAssign('sort_order_select', $select->select($this->getSortOrder($obj, $entries)));		
		
		
		$block = ($this->controller->action == 'question') ? 'member_question' : 'question';
		$tpl->tplSetNeeded('/'. $block);

		$tpl->tplAssign($this->setCommonFormVars($obj));
		$tpl->tplAssign($this->setStatusFormVars($obj->get('active')));
		$tpl->tplAssign($obj->get());
		$tpl->tplAssign($this->msg);
		
		$tpl->tplParse();
		return $tpl->tplPrint(1);
	}
	
	
	function ajaxGetCategoryRoles($category_id) {
		$manager = &new KBCategoryModel();
		return CommonEntryView::ajaxGetCategoryRoles($category_id, $manager);
	}
	
	
	function getPrivateCategoryMsg(&$manager, $category_id) {
		return CommonEntryView::getPrivateCategoryMsg($manager, $category_id);
	}
	
	
	// SORT ORDER // ----------------------------
	
	function ajaxPopulateSortSelect($category_id) {
		
		$entries = $this->manager->getSortRecords($category_id);
		
		$objResponse = new xajaxResponse();
		$objResponse->setCharEncoding($this->encoding);
		
		//$objResponse->addAlert($category_id);
		//$objResponse->addScriptCall ("populateSelect", "$vars");
	
		$i = 0; 
		$option = "sel.options[%d] = new Option('%s','%s');";
	
		$objResponse->addScript("var sel = document.getElementById('sort_order');");
		$objResponse->addScript("sel.options.length = 0;");	
		
		foreach($this->getSortSelectRange($entries) as $k => $v) {
			$v = addslashes($v);
			$objResponse->addScript(sprintf($option, $i++, $v, $k));
		}
	
		// selected, try to remmeber original value
		$sort_order = false;
		if($this->obj->get('id')) {
			$sort_order = $this->getSortOrder($this->obj, $entries, true);
		}
		
		if($sort_order) { 
			$objResponse->addScript("sel.value = $sort_order;");
		} else {
			$objResponse->addScript("sel.selectedIndex = 1;");
		}
	
		return $objResponse;	
	}
	
	
	function getSortSelectRange($rows) {
		
		$j = 1;
		$search = array("#(\r\n|\n)#"); // "#\n+#",
		$data = array();
		$data['sort_begin'] = 'AT THE BEGINNING';
		$data['sort_end'] = 'AT THE END (default)';
		foreach($rows as $id => $v) {
			$title = preg_replace($search, '', $v['title']);
			$title = substr($title, 0, 70);
			//$data[$id . '_' . $v['sort_order']] = sprintf("%s. AFTER: %s", $j++, $title);
			$data[$id] = sprintf("%s. AFTER: %s", $j++, $title);
		}
		
		return $data;
	}
	
	
	function getSortOrder($obj, $entries, $ajax = false) {
			
			if($_POST && $ajax == false) {
				$sort_order = $_POST['sort_order'];
			} else {
				$entry_id = $obj->get('id');
				$sort_order = $obj->get('sort_order');
				$found = false;
				
				if($sort_order != 'sort_begin' && $sort_order != 'sort_end') {
					foreach($entries as $id => $v) {
						if($id == $entry_id) {
							$found = true;
							$sort_order = (isset($prev_id)) ? $prev_id : 'sort_begin';
							break;
						}
						
						$prev_id = $id;
					}
				}
			}
			
			if($ajax && !$found) {
				$sort_order = false;
			}
			
			return $sort_order;	
		}	
}
?>